package com.bailun91.auth.service.Impl;

import com.bailun91.auth.entity.JsonData;
import com.bailun91.auth.entity.User;
import com.bailun91.auth.jwt.JwtToken;
import com.bailun91.auth.jwt.JwtUtil;
import com.bailun91.auth.mapper.UserMapper;
import com.bailun91.auth.service.LoginService;
import com.bailun91.auth.util.BeanUtil;
import com.bailun91.auth.util.Constants;
import com.bailun91.auth.util.ShiroUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Override
    public JsonData login(String userName, String password, HttpServletRequest request, HttpServletResponse response) {

        User user = userMapper.findByUsername(userName);
        if (null == user){
            return JsonData.buildError("账号错误");
        }

        password = ShiroUtils.sha256(password,Constants.SALT);

        if (!password.equals(user.getPassword())){
            return JsonData.buildError("密码错误");
        }

        String accessToken = JwtUtil.createJWT(userName,request);
        if (null != accessToken){
            response.setHeader(Constants.ACCESS_TOKEN_NAME, accessToken);
            response.setHeader("Access-Control-Expose-Headers", Constants.ACCESS_TOKEN_NAME);
        }

        //设置refreshToken
        redisTemplate.opsForValue().set(Constants.REFRESHTOKENPRE_CRM + userName,accessToken,Constants.REFRESH_TOKEN_EXP_TIME, TimeUnit.SECONDS);
        return JsonData.buildSuccess(accessToken, "登录成功");
    }

    @Override
    public JsonData logout(HttpServletRequest request, HttpServletResponse response) {

        //清除redis缓存中的refreshToken
        String token = response.getHeader(Constants.ACCESS_TOKEN_NAME);
        String username = JwtUtil.getUserNameFromToken(token);

        String refreshToken = (String) redisTemplate.opsForValue().get(Constants.REFRESHTOKENPRE_CRM + username);
        if (null != refreshToken) {
        SecurityUtils.getSubject().logout();
        redisTemplate.opsForValue().set(Constants.REFRESHTOKENPRE_CRM + username,token,0,TimeUnit.SECONDS);
        }
        return null;
    }
}
